package com.epam.tcs.dao.hibernate.impl;

import java.util.List;

import org.hibernate.Hibernate;
import org.hibernate.Session;

import com.epam.tcs.dao.factory.GroupDAO;
import com.epam.tcs.dao.hibernate.ConnectionFactory;
import com.epam.tcs.dao.hibernate.entities.Group;

public class GroupDAOHibernateImpl extends ElementDAOHibernateImpl<Group>
		implements GroupDAO {

	public GroupDAOHibernateImpl(Class<?> objType) {
		this.objType = objType;
	}

	@Override
	public Group getElement(long id) {
		Session session = ConnectionFactory.getOrInitSession();
		Group group = (Group) session.load(objType, id);
		Hibernate.initialize(group.getStudents());

		Hibernate.initialize(group.getProgram());
		session.close();
		return group;
	}

	@Override
	public List<Group> getAllElements() {
		Session session = ConnectionFactory.getOrInitSession();
		List<Group> groups = (List<Group>) session.createQuery(
				"from " + objType.getName()).list();

		for (Group group : groups) {
			Hibernate.initialize(group.getStudents());
			Hibernate.initialize(group.getProgram());
		}

		session.close();
		return groups;
	}

	public List<Group> getRangeElements(int start, int count) {
		Session session = ConnectionFactory.getOrInitSession();
		List<Group> groups = (List<Group>) session.createQuery(
				"from " + objType.getName() + " LIMIT (" + start + "," + count + ")").list();

		for (Group group : groups) {
			Hibernate.initialize(group.getStudents());

			Hibernate.initialize(group.getProgram());
		}

		session.close();
		return groups;
	}

}
